package cn.xyt.util;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import cn.xyt.dto.SystemProperty;

import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor.CallerRunsPolicy;

@Service("messageThreadPool")
public class MessageThreadPool {
	private static final ThreadPoolTaskExecutor poolTaskExecutor = new ThreadPoolTaskExecutor();;
	@Autowired
	private SystemProperty poperty;

	@PostConstruct
	public void init() {
		int corePoolSize = this.poperty.getCorePoolSize();
		int maxPoolSize = this.poperty.getMaxPoolSize();
		int queueCapacity = this.poperty.getQueueCapacity();
		int keepAliveSeconds = this.poperty.getKeepAliveSeconds();
		String threadNamePrefix = this.poperty.getThreadNamePrefix();
		RejectedExecutionHandler rejectedExecutionHandler = new CallerRunsPolicy();
		
		poolTaskExecutor.setCorePoolSize(corePoolSize);
		poolTaskExecutor.setMaxPoolSize(maxPoolSize);
		poolTaskExecutor.setQueueCapacity(queueCapacity);
		poolTaskExecutor.setKeepAliveSeconds(keepAliveSeconds);
		poolTaskExecutor.setRejectedExecutionHandler(rejectedExecutionHandler);
		poolTaskExecutor.setThreadNamePrefix(threadNamePrefix);

		poolTaskExecutor.initialize();
	}

	@PreDestroy
	public void destroy() {
		poolTaskExecutor.destroy();
	}

	public static void executeMessageTask(Runnable task) {
		try {
			poolTaskExecutor.execute(task);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
 }

